import {useEffect} from "react";
import {
    RTCPeerConnection,
    RTCSessionDescription,
    RTCIceCandidate,
    mediaDevices,
} from "react-native-webrtc";

import {useWebRTCCallActions, useWebRTCCallState} from "@/hooks/webrtc/webrtc-call";
import {useStompSend} from "@/hooks/stomp/stomp-send";
import {SignalType} from "@/types/webrtc";
import {ChatUser} from "@/types/chat-message";

export function useWebRTCCall(currentUser: ChatUser) {
    const state = useWebRTCCallState();
    const actions = useWebRTCCallActions()
    const {sendRTCMessage} = useStompSend();

    // 1. 创建本地 PeerConnection
    const createPC = (receiverId: string): RTCPeerConnection => {
        const pc = new RTCPeerConnection({
            iceServers: [
                {
                    urls: ["turn:www.beloved.ltd:5349"],
                    username: "cirno",
                    credential: "webrtc",
                },
            ]
        });

        // 收集 ICE 候选
        pc.addEventListener("icecandidate", (event) => {
            if (event.candidate) {
                sendRTCMessage({
                    type: SignalType.CANDIDATE,
                    receiver: receiverId,
                    payload: event.candidate,
                    user: currentUser,
                });
            }
        });

        pc.addEventListener("track", (event) => {
            const [remoteStream] = event.streams;
            actions.setRemoteStream(remoteStream);
        });

        actions.setPeerConnection(pc);
        return pc;
    };

    // 2. 发起呼叫（发送 offer）
    const callUser = async (receiverId: string) => {
        const stream = await mediaDevices.getUserMedia({audio: true, video: true});
        actions.setLocalStream(stream);

        const pc = createPC(receiverId);
        stream.getTracks().forEach((track) => pc.addTrack(track, stream));

        const offer = await pc.createOffer({});
        await pc.setLocalDescription(offer);

        sendRTCMessage({
            type: SignalType.OFFER,
            receiver: receiverId,
            payload: offer,
            user: currentUser,
        });
    };

    // 3. 接收到 offer（创建 answer）
    const handleOffer = async (payload: any, senderId: string) => {
        const stream = await mediaDevices.getUserMedia({audio: true, video: true});
        actions.setLocalStream(stream);

        const pc = createPC(senderId);
        stream.getTracks().forEach((track) => pc.addTrack(track, stream));

        await pc.setRemoteDescription(new RTCSessionDescription(payload));
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);

        sendRTCMessage({
            type: SignalType.ANSWER,
            receiver: senderId,
            payload: answer,
            user: currentUser,
        });
    };

    // 4. 接收到 answer
    const handleAnswer = async (payload: any) => {
        const pc = state.peerConnection;
        if (!pc) return;
        await pc.setRemoteDescription(new RTCSessionDescription(payload));
    };

    // 5. 接收到 ICE 候选
    const handleCandidate = async (candidate: any) => {
        const pc = state.peerConnection;
        if (!pc) return;
        try {
            await pc.addIceCandidate(new RTCIceCandidate(candidate));
        } catch (err) {
            console.error("添加候选失败", err);
        }
    };

    // 6. 挂断通话
    const hangUp = () => {
        actions.reset();
    };

    // 7. 页面卸载自动清理
    useEffect(() => {
        return () => {
            hangUp();
        };
    }, []);

    return {
        callUser,
        handleOffer,
        handleAnswer,
        handleCandidate,
        hangUp,
        localStream: state.localStream,
        remoteStream: state.remoteStream,
    };
}

